package com.yiren.dbaa.module.practice_set.site.presenter;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import com.yiren.backstage.config.api.LoadConfigApi;
import com.yiren.backstage.config.bean.device.UserParamConfigBean;
import com.yiren.backstage.currency.entity.SiteEntity;
import com.yiren.backstage.currency.utils.StringUtil;
import com.yiren.backstage.db.dao.controller.UserDbController;
import com.yiren.dbaa.currency.api.CommonCallBack;
import com.yiren.dbaa.currency.dialog.CommonDialog;
import com.yiren.dbaa.module.practice_set.site.bean.CompanyBean;
import com.yiren.dbaa.module.practice_set.site.bean.ModifyValBean;
import com.yiren.dbaa.module.practice_set.site.contract.AddSiteRuleInfoContract;
import com.yiren.dbaa.module.practice_set.site.contract.SiteRuleContract;
import com.yiren.dbaa.module.practice_set.site.model.AddSiteRuleInfoModel;
import com.yiren.dbaa.module.practice_set.site.model.SiteRuleModel;
import com.yiren.dbaa.module.practice_set.PracticeCarSetActivity;
import com.yiren.dbaa.module.project_edit.view.activity.ProjectManageActivity;
import com.yiren.dbaa.view.dialog.LoadDialog;
import com.yiren.dbaa.view.toast.MessageBox;

import java.util.List;

/**
 * @author lwb
 * @date : 2022/10/21 14:28
 * @description: 新建规则信息页P
 */
public class AddSiteRuleInfoPresenter implements AddSiteRuleInfoContract.Presenter {

    private Activity activity;
    private SiteRuleContract.Model siteRuleModel;
    private AddSiteRuleInfoContract.Model addSiteRuleInfoMode;

    public AddSiteRuleInfoPresenter(Activity activity) {
        this.activity = activity;
        siteRuleModel = new SiteRuleModel(activity);
        addSiteRuleInfoMode = new AddSiteRuleInfoModel(activity);
    }

    @Override
    public void loadSiteRuleFromServer(AddSiteRuleInfoContract.View view) {
        UserParamConfigBean userParamConfigBean = LoadConfigApi.loadUserParamConfig(activity);
        siteRuleModel.getSiteRuleFromServer(userParamConfigBean.getUserInfo().getId().toString(),true, new CommonCallBack() {
            @Override
            public void success(Object result) {
                view.showSiteRuleSource((List<SiteEntity>) result);
            }

            @Override
            public void fail(String error) {
                MessageBox.show(activity, "服务器数据加载失败");
            }
        });


    }


    @Override
    public void loadAllCompany(AddSiteRuleInfoContract.View view) {
        addSiteRuleInfoMode.getAllCompany(new CommonCallBack() {
            @Override
            public void success(Object result) {
                List<CompanyBean> companyList = (List<CompanyBean>) result;
                view.showCompany(companyList);
            }

            @Override
            public void fail(String error) {
                MessageBox.show(activity, error);
            }
        });
    }

    @Override
    public void loadCitySiteName(String citypid, AddSiteRuleInfoContract.View view) {
        addSiteRuleInfoMode.getCitySiteName(citypid, new CommonCallBack() {
            @Override
            public void success(Object result) {
                List<SiteEntity> citySiteList = (List<SiteEntity>) result;
                view.showSiteName(citySiteList);
            }

            @Override
            public void fail(String error) {
                MessageBox.show(activity, error);
            }
        });
    }

    @Override
    public void loadNewBaseRule(CommonCallBack callBack) {
        siteRuleModel.getNewBaseRule(callBack);
    }

    @Override
    public void saveSiteRule(List<SiteEntity> serviceSites,SiteEntity siteRulesource,SiteEntity newSite) {
        SiteEntity existsSite = null;
        //判断新建考规 服务器是否存在
        if (null != serviceSites && serviceSites.size() > 0) {
            for (SiteEntity serviceSite : serviceSites) {
                if (serviceSite.getSiteCode().equals(newSite.getSiteCode())) {
                    existsSite = serviceSite;
                    break;
                }
            }
        }
        if(null == existsSite){
            //判断新建考规 本地是否存在  这种场景是未公开考规
            List<SiteEntity> siteLoaclList = UserDbController.getInstance(false).queryAll(SiteEntity.class);
            if(null != siteLoaclList && siteLoaclList.size() > 0){
                for (SiteEntity site : siteLoaclList) {
                    if (site.getSiteCode().equals(newSite.getSiteCode())) {
                        existsSite = site;
                        break;
                    }
                }
            }
        }

        if (null != existsSite) {
            SiteEntity finalExistsSite = existsSite;
            CommonDialog.showTwoBtn(activity, "操作确认", "您已新建" + finalExistsSite.getSiteName() + "，新建会将本地考规覆盖，确定覆盖新建吗？", "取消", "覆盖新建", (dialog, which) -> {
                if (which == -2) {
                } else {
                    downloadSiteRule(finalExistsSite,siteRulesource,newSite);
                }
                dialog.dismiss();
            });
        } else {
            //下载考规数据
            downloadSiteRule(null,siteRulesource,newSite);
        }
    }

    /**
     * 下载数据
     * @param existsSite
     * @param siteRulesource
     * @param newSite
     */
    private void downloadSiteRule(SiteEntity existsSite,SiteEntity siteRulesource,SiteEntity newSite) {
        //下载官方模板数据
        LoadDialog.show(activity, "正在下载数据，请稍候...");
        newSite.setBaseVer(siteRulesource.getBaseVer());
        siteRuleModel.downLoadBaseData(newSite, new CommonCallBack() {
            @Override
            public void success(Object result) {
                if (!StringUtil.isEmpty(siteRulesource.getSiteCode())) {
                    //下载修改的数据
                    siteRuleModel.downLoadModifyVal(Integer.parseInt(siteRulesource.getUserId()), siteRulesource.getSiteCode(), siteRulesource.getRuleVer(), new CommonCallBack() {
                        @Override
                        public void success(Object result) {
                            LoadDialog.dismiss(activity);
                            ModifyValBean modifyValBean = (ModifyValBean) result;
                            if(null == existsSite){
                                //第一次新建
                                insertOrReplaceSite(modifyValBean,newSite,0);
                            }else{
                                //下载数据来源的基础模板数据和修改参数，更新自己基础数据版本和合伙人修改参数字段
                                insertOrReplaceSite(modifyValBean,newSite,existsSite.getRuleVer());
                            }
                        }

                        @Override
                        public void fail(String error) {
                            MessageBox.show(activity, "数据下载失败!");
                        }
                    });
                } else{
                    LoadDialog.dismiss(activity);
                    if(null == existsSite){
                        //第一次新建
                        insertOrReplaceSite(null,newSite,0);
                    }else{
                        //下载数据来源的基础模板数据和修改参数，更新自己基础数据版本和合伙人修改参数字段
                        insertOrReplaceSite(null,newSite,existsSite.getRuleVer());
                    }
                }
            }

            @Override
            public void fail(String error) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        CommonDialog.showOneBtn(activity, "操作提示", "下载基础模板数据失败，无法新建规则！", "我知道了", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                    }
                });
            }
        });
    }

    private void insertOrReplaceSite(ModifyValBean modifyValBean,SiteEntity newSite,float ruleVer){
        Intent intent = new Intent(activity, ProjectManageActivity.class);
        Bundle bundle = new Bundle();
        newSite.setRuleVer(ruleVer);
        if(null == modifyValBean){
            newSite.setPartneModifyVal("");
        }else{
            newSite.setPartneModifyVal(modifyValBean.getPartneModifyVal());
        }
        newSite.setCoachModifyVal("");
        UserDbController.getInstance(false).insertOrReplace(newSite);
        bundle.putSerializable("site", newSite);

        activity.runOnUiThread(() -> CommonDialog.showTwoBtn(activity, "操作确认", "新建成功，请问现在编辑规则吗？", "返回", "编辑规则", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == -2) {
                    activity.finish();
                    activity.startActivity(new Intent(activity, PracticeCarSetActivity.class));
                } else {
                    intent.putExtras(bundle);
                    activity.startActivity(intent);
                }
                dialog.dismiss();
            }
        }));
    }
}

